package com.cloud.apigateway.filter;

import com.cloud.apigateway.util.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 *describe: 自定义权限 过滤器
 *
 *@author zhanghaixuan
 *@date 2018/10/02
 **/
@Component
public class AuthFilter extends ZuulFilter{
	@Autowired
	private StringRedisTemplate redisTemplate;

	/**
	 * 定义的过滤器类型 此处为  pre
	 * @return FilterConstants
	 */
	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	/**
	 * 自定义过滤器的位置  此处是模拟实现检查token  所以要放在最前面
	 * @return
	 */
	@Override
	public int filterOrder() {
		return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	/**
	 * filter中具体的实现卸载run方法中
	 * @return
	 * @throws ZuulException 抛出的异常
	 */
	@Override
	public Object run() throws ZuulException {
		/**
		 * zuul定义的 RequestContext 可以获取到当前的请求
		 */
		RequestContext currentContext = RequestContext.getCurrentContext();
		HttpServletRequest request = currentContext.getRequest();
		/**
		 * 具体的业务逻辑
		 * /order/create 只能买家访问
		 * /order/finish 只能卖家访问
		 * /product/list 买家卖家都能访问
		 */

		if("/order/order/create".equals(request.getRequestURI())){
			Cookie openid = CookieUtil.get(request, "openid");

			if(openid == null || StringUtils.isEmpty(openid.getValue())){
				currentContext.setSendZuulResponse(false);
				currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
			}
		}

		if("/order/order/finish".equals(request.getRequestURI())){
			Cookie token = CookieUtil.get(request, "token");

			if(token == null
					|| StringUtils.isEmpty(token.getValue())
					|| StringUtils.isEmpty(redisTemplate.opsForValue().get(String.format("token_",token.getValue())))){
				currentContext.setSendZuulResponse(false);
				currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
			}
		}

		return  null;
	}
}

